﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace RMS.Utils.Histogram
{
    public class Histogram : IHistogram
    {
        private Bitmap bmpLoaded = null;
        private byte[,] Grey;
        private byte[] HiGrey;

        public byte[] GetHistogram(string path)
        {
            if (bmpLoaded != null)
                bmpLoaded.Dispose();
            bmpLoaded = new Bitmap(path);
            int y = bmpLoaded.Height;
            int x = bmpLoaded.Width;
            Grey = new byte[bmpLoaded.Height, bmpLoaded.Width];
            HiGrey = new byte[256];
            BitmapToMatrix(bmpLoaded);
            return GenerateHistogram();
        }
        private void BitmapToMatrix(Bitmap BMP)
        {
            BitmapData bitmapData = BMP.LockBits(new Rectangle(0, 0,
              BMP.Width, BMP.Height),
              ImageLockMode.ReadOnly,
              PixelFormat.Format32bppArgb);
            int a = 0;
            unsafe
            {
                byte* imagePointer = (byte*)bitmapData.Scan0;

                for (int i = 0; i < bitmapData.Height; i++)
                {
                    for (int j = 0; j < bitmapData.Width; j++)
                    {
                        a = (byte)(0.229 * (double)imagePointer[0] + 0.587 * (double)imagePointer[1] +
                             0.114 * (double)imagePointer[2]);
                        Grey[i, j] = (byte)a; ;
                        imagePointer += 4;
                    }
                    imagePointer += bitmapData.Stride -
                        (bitmapData.Width * 4);
                }
            }
            BMP.UnlockBits(bitmapData);
        }
        private byte[] GenerateHistogram()
        {
            for (int i = 0; i < bmpLoaded.Height; i++)
            {
                for (int j = 0; j < bmpLoaded.Width; j++)
                {
                    HiGrey[Grey[i, j]]++;
                }
            }
            return HiGrey;
        }
        public override string ToString()
        {
            String x = null;
            for (int i = 0; i < 256; i++)
            {
                x += HiGrey[i].ToString();
            }
            return x;
        }
    }
}
